<?php
/**
 * Created by PhpStorm
 * User: lcz
 * Date: 2019/10/23
 * Time: 10:39
 * 战区
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\AgentShipment;
use app\common\model\AgentShop;
use app\common\service\UserService;
use think\Cache;
use think\Db;
use app\admin\model\User as UserModel;

class Theater extends Api {
	
	/**
	 * 统计
	 */
	public function statistics() {
		$userId = $this->auth->id;
		$level = $this->auth->level;
		
		$isAdmin = false;
		if($level != UserModel::LEVEL_THEATER) {
			$adminLevel = \app\common\model\AgentAdmin::getAdminLevel($userId);
			if(!$adminLevel || $adminLevel['role'] != UserModel::LEVEL_THEATER) {
				$this->error('权限不足');
			}
			$isAdmin = true;
			$userId = $adminLevel['user_id'];
		}
		
		$agentInfo = AgentShop::getInfoByUserId($userId);
		if(!$agentInfo || $agentInfo['status'] == AgentShop::STATUS_D) {
			$this->error('当前身份已被禁用');
		}
		
		//统计发展中心，提货点和场景店的数量
		$count = Db::name('agentShop')
			->where([
				'theater_id' => $agentInfo['id'],
				'status' => AgentShop::STATUS_Y,
				'role' => ['in', [UserModel::LEVEL_SHOP, UserModel::LEVEL_WAREHOUSE, UserModel::LEVEL_CENTER]]
				])
			->group('role')
			->column('count(*)', 'role');
		
		/**
		 * 查看自己及下级的代理ID
		 */
		$agents = Db::name('agentShop')
			->where(['theater_id' => $agentInfo['id'], 'status' => AgentShop::STATUS_Y])
			->column('user_id', 'id');
		//推广员
		$ids = array_values($agents);
		$ids[] = $userId;
		$promotion = Db::name('promotion')
			->where([
				'recommend_user_id' => ['in', $ids],
				'status' => \app\common\model\Promotion::STATUS_Y
			])->count();
		
		/**
		 * 待签收入库订单数量
		 */
		$orderNumber = Db::name('agentShipment')
			->where(['sign_agent_id' => $agentInfo['id'], 'status' => AgentShipment::STATUS_WAIT])
			->count();
		
		//我的奖励数量
		$user = $this->auth->getUser();
		$selfNumber = $user['reward_number'];
		
		//我场景店的奖励数量
		$rewardNumber = Db::name('agentShop')->alias('a')
			->join('user u', 'a.user_id = u.id', 'left')
			->where(['a.theater_id' => $agentInfo['id'], 'a.status' => AgentShop::STATUS_Y])
			->sum('u.reward_number');
		
		//粉丝
		$fans = UserService::getFansNumById($userId);
		$this->success('查询成功', [
			'fans' => $fans,
			'order_number' => $agentInfo['order_number'],
			'sale_number' => $agentInfo['sale_number'],
			'order_amount' => $agentInfo['sale_amount'],
			'center' => $count[UserModel::LEVEL_CENTER] ??0,
			'stock_order_number' => $orderNumber,
			'warehouse' => $count[UserModel::LEVEL_WAREHOUSE] ??0,
			'shop' => $count[UserModel::LEVEL_SHOP] ??0,
			'promotion' => $promotion,
			'agentInfo' => $agentInfo,
			'is_admin' => $isAdmin,
			'self_number' => $selfNumber,
			'reward_number' => $rewardNumber,
		]);
	}
	
	
	/**
	 * 下级所有列表
	 */
	public function agentMap() {
		
		$userId = $this->auth->id;
		$key = $this->request->path().md5($this->request->controller().$this->request->action().$userId);
		if(!$list = Cache::get($key)) {
			$agent = AgentShop::get(['user_id' => $userId]);
			$where =[
				'theater_id' => $agent['id'],
				'status' => AgentShop::STATUS_Y
			];
			
			$obj = Db::name('agentShop');
			$field = 'id, name, mobile, lat, lng, role';
			
			$agents = $obj
				->where($where)
				->field($field)
				->select();
			
			$list = [];
			if($agents) {
				$index = 0;
				foreach ($agents as $agent) {
					$list[] = [
						'id' => $index,
						'latitude' => $agent['lat'],
						'longitude' => $agent['lng'],
						'iconPath' => $agent['role'] == 3 ?'/static/location_shop.png' :'/static/location.png',
						'width' => 30,
						'height' => 30,
						'title' => $agent['name'].'('.$agent['mobile'].')',
					];
					$index ++;
				}
			}
			Cache::set($key, $list, 600);
		}
		
		$this->success('查询成功', $list);

	}
	
	/**
	 * 排行
	 */
	public function ranking() {
		
		$userId = $this->auth->id;
		$level = $this->auth->level;
		if($level != UserModel::LEVEL_THEATER) {
			$adminLevel = \app\common\model\AgentAdmin::getAdminLevel($userId);
			if(!$adminLevel || $adminLevel['role'] != UserModel::LEVEL_THEATER) {
				$this->error('权限不足');
			}
			$userId = $adminLevel['user_id'];
		}
		
		$agentInfo = AgentShop::getInfoByUserId($userId);
		$role = $this->request->get('role');
		
		
		if($role == UserModel::LEVEL_PROMOTION) {
			$agents = Db::name('agentShop')
				->where(['theater_id' => $agentInfo['id'], 'status' => AgentShop::STATUS_Y])
				->column('user_id', 'id');
			
			//推广员
			$ids = array_values($agents);
			$ids[] = $userId;
			
			$rows = Db::name('promotion')->alias('p')
				->join('user u', 'u.id = p.user_id', 'left')
				->order(['p.sale_number' => 'desc'])
				->where([
					'p.recommend_user_id' => ['in', $ids],
					'p.sale_number' => ['gt', 0],
					'p.status' => \app\common\model\Promotion::STATUS_Y])
				->limit(10)
				->field('p.name, u.nickname, p.sale_number')
				->select();
		} else {
			$rows = Db::name('agentShop')->alias('p')
				->join('user u', 'u.id = p.user_id', 'left')
				->order(['p.sale_number' => 'desc'])
				->where([
					'p.role' => $role,
					'p.sale_number' => ['gt', 0],
					'p.theater_id' => $agentInfo['id'],
					'p.status' => AgentShop::STATUS_Y])
				->limit(10)
				->field('u.nickname, p.sale_number, p.name')
				->select();
		}
		
		$this->success('查询成功', $rows);
	}
}
